/*=====================================================
Critical Links
Auto Configuration Server

Authors:
	Rui Eduardo Gouveia Gil - r-gil@critical-links.com

Date: 2010
Version 0.1
=======================================================*/
#include "httpd/HttpUserManager.h"
#include "database/DataBase.h"

namespace acs
{

HttpUserManager::HttpUserManager() : pion::net::PionUserManager()
{
	pion::net::PionUserManager::addUser("_","_");
}

HttpUserManager::~HttpUserManager()
{

}

bool HttpUserManager::addUser(const std::string &username, const std::string &password)
{
	Throw(rgcpp::IllegalStateException("Invalid use of HttpUserManager: addUser"));
}

bool HttpUserManager::updateUser(const std::string &username, const std::string &password)
{
	Throw(rgcpp::IllegalStateException("Invalid use of HttpUserManager: updateUser"));
}

bool HttpUserManager::addUserHash(const std::string &username, const std::string &password_hash)
{
	Throw(rgcpp::IllegalStateException("Invalid use of HttpUserManager: addUserHash"));
}

bool HttpUserManager::updateUserHash(const std::string &username, const std::string &password_hash)
{
	Throw(rgcpp::IllegalStateException("Invalid use of HttpUserManager: updateUserHash"));
}

bool HttpUserManager::removeUser(const std::string &username)
{
	Throw(rgcpp::IllegalStateException("Invalid use of HttpUserManager: removeUser"));
}

pion::net::PionUserPtr HttpUserManager::getUser(const std::string &username)
{
	if(DataBase::getInstance()->existsUser(username))
	{
		User user = DataBase::getInstance()->getUser(username);

		pion::net::PionUserPtr userPtr(new pion::net::PionUser(user.getLogin()));
		userPtr->setPassword(user.getPassword());

		return userPtr;
	}
	else
		return pion::net::PionUserPtr();
}

pion::net::PionUserPtr HttpUserManager::getUser(const std::string& username, const std::string& password)
{
	if(DataBase::getInstance()->existsUser(username))
	{
		User user = DataBase::getInstance()->getUser(username);

		if(user.validatePassword(password))
		{
			pion::net::PionUserPtr userPtr(new pion::net::PionUser(user.getLogin()));

			userPtr->setPassword(user.getPassword());

			return userPtr;
		}
		else
			return pion::net::PionUserPtr();
	}
	else
		return pion::net::PionUserPtr();
}

User HttpUserManager::getCurrentUser()
{
	unsigned int threadId = pthread_self();

	if(this->userThreadBind.find(threadId) != this->userThreadBind.end() && DataBase::getInstance()->existsUser(this->userThreadBind[threadId]))
		return DataBase::getInstance()->getUser(this->userThreadBind[threadId]);

	return User();
}

void HttpUserManager::attachUserToThread(std::string userName)
{
	this->userThreadBind[pthread_self()] = userName;
}

void HttpUserManager::detachUserToThread()
{
	this->userThreadBind.erase(pthread_self());
}

}
